package git.soulbgm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import git.soulbgm.common.base.BaseController;
import git.soulbgm.common.pojo.QueryDto;
import git.soulbgm.common.pojo.Response;
import git.soulbgm.pojo.DictType;
import git.soulbgm.service.DictDataService;
import git.soulbgm.service.DictTypeService;
import git.soulbgm.utils.EasyPoiUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static git.soulbgm.common.MonitorConstants.*;

/**
 * 字典类型控制器
 *
 * @author SoulBGM
 * @date 2022/03/25 17:15
 */
@RestController
@RequestMapping("system/dict/type")
public class DictTypeController extends BaseController {

    private final DictTypeService dictTypeService;
    private final DictDataService dictDataService;

    public DictTypeController(DictTypeService dictTypeService, DictDataService dictDataService) {
        this.dictTypeService = dictTypeService;
        this.dictDataService = dictDataService;
    }

    @PostMapping("list")
    public Response list(@RequestBody QueryDto<DictType> dto, Page<DictType> queryPage) {
        Page<DictType> resultPage = dictTypeService.page(queryPage, new QueryWrapper<>(dto.getData()));
        return success(resultPage);
    }

    @GetMapping("export")
    public void export(DictType info, HttpServletResponse response) {
        List<DictType> list = dictTypeService.list(new QueryWrapper<>(info));
        try {
            EasyPoiUtil.exportExcel(response, "字典类型数据", list, DictType.class);
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }

    @PostMapping("add")
    public Response add(DictType info) {
        boolean result = dictTypeService.save(info);
        return result ? success() : error();
    }

    @PostMapping("remove")
    public Response remove(String ids) {
        boolean result = dictTypeService.removeByIds(Arrays.asList(ids.split(",")));
        return result ? success() : error();
    }

    @PostMapping({"changeStatus",  "edit"})
    public Response edit(DictType info) {
        boolean result = dictTypeService.updateById(info);
        return result ? success() : error();
    }

    @GetMapping("refreshCache")
    public Response refreshCache() {
        dictDataService.refreshCache();
        return success();
    }

    @PostMapping("checkDictTypeUnique")
    public String checkNodeCodeUnique(DictType info) {
        return dictTypeService.checkUnique(info) ? UNIQUE : NOT_UNIQUE;
    }

}
